import { HttpException, HttpStatus, Injectable, Inject, Session } from '@nestjs/common';
import * as svgCaptcha from 'svg-captcha';
import { jwtConstants } from 'src/utils/constant';
import { v4 as uuidv4 } from 'uuid';

@Injectable()
export class CaptchaService {
	private captchaStore = new Map<string, { text: string, expires: number }>();


  async generateCaptcha(session) {
		const captcha = svgCaptcha.create({
			ignoreChars: 'i1o0l'
		})

		const expires = Date.now() + 60 * 1000; // 1 分钟有效期
		session.verifyCodeInfo = JSON.stringify({expires, text: captcha.text})
    return captcha.data;
	}

	verifyCaptcha(ipt: string, session): boolean {
		const verifyCodeInfo = JSON.parse(session.verifyCodeInfo || '{}')
		if (Number(verifyCodeInfo.expires || 0) > Date.now()) {
			if (verifyCodeInfo.text === ipt) {
				// session.verifyCodeInfo = JSON.stringify({})
				return true;
			}
			throw new HttpException('验证码错误', HttpStatus.BAD_REQUEST);
    }
		throw new HttpException('验证码超时', HttpStatus.BAD_REQUEST);
	}
}
